const express = require("express");
const app = express();

// 中间件
// http://127.0.0.1:8080/index.html

// function static(param) {
//   return (req, res, next) => {
//     //请求方式
//     if (req.method === "GET") {
//       const path = req.path; //资源路径
//       res.sendFile(`${param}/${path}`); // f:/www/imgs/2.jpg
//     } else {
//       next();
//     }
//     // next();
//   };
// }
// app.use(static("f:/www"));

// 设置根目录
// http://127.0.0.1:8080/index.html
// app.use(express.static("./public")); // 匹配/index.html
app.get("/index.html", (req, res) => {
  res.send("hello index");
});
app.use(express.static("f:/www")); // 匹配/index.html

// express app
// http://127.0.0.1:8080/
// http-server -p 8080

// http://127.0.0.1:8080/index.html

// app.use(({ method, path }, res, next) => {
//   if (method === "GET" && path === "/index.html") {
//     res.send("hello");
//   } else {
//     next();
//   }
// });

app.get("/index.html", (req, res) => {
  res.send("hello index");
});
// GET http://127.0.0.1:8080/imgs/2.jpg HTTP/1.1
app.get("/imgs/2.jpg", (req, res) => {
  res.send("hello 2.jpg");
});

// POST http://127.0.0.1:8080/users HTTP/1.1
app.post("/users", (req, res) => {
  res.send("hello users");
});

// PUT http://127.0.0.1:8080/update HTTP/1.1
app.put("/update", (req, res) => {
  res.send("hello update");
});

// PATCH http://127.0.0.1:8080/update/one HTTP/1.1
app.patch("/update/one", (req, res) => {
  res.send("hello update one");
});

// DELETE http://127.0.0.1:8080/remove HTTP/1.1
app.delete("/remove", (req, res) => {
  res.send("hello remove");
});

app.get("/json", (req, res) => {
  res.send({
    username: "jack",
    age: 20,
    gender: "boy",
  });
});

app.get("/html", (req, res) => {
  res.send("<b>hello html</b>");
});

app.get("/xml", (req, res) => {
  res.type("xml");
  res.status(200);
  res.send(`
    <user>
        <username>jack</username>
        <age>30</age>
        <gender>boy</gender>
    </user>
  `);
});

app.listen(8080, () => {
  //服务器启动成功后执行
  console.log("http://127.0.0.1:8080");
});
